package com.activemq.demo.activemq_service.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicLong;

@Service
public class MessageProcessingService {

    private static final Logger logger = LoggerFactory.getLogger(MessageProcessingService.class);

    private final AtomicLong processedCount = new AtomicLong(0);
    private final AtomicLong failedCount = new AtomicLong(0);
    private final AtomicLong deadLetterCount = new AtomicLong(0);

    public boolean processMessage(String messageId, String content) {
        logger.info("处理消息 - ID: {}, 内容: {}", messageId, content);

        try {
            // 模拟业务处理逻辑
            boolean success = executeBusinessLogic(content);

            if (success) {
                processedCount.incrementAndGet();
                logger.info("业务处理成功 - ID: {}", messageId);
                return true;
            } else {
                failedCount.incrementAndGet();
                logger.warn("业务处理失败 - ID: {}", messageId);
                return false;
            }

        } catch (Exception e) {
            failedCount.incrementAndGet();
            logger.error("业务处理异常 - ID: {}, 错误: {}", messageId, e.getMessage(), e);
            return false;
        }
    }

    public void handleDeadLetterMessage(String messageId, String content) {
        deadLetterCount.incrementAndGet();
        logger.warn("处理死信消息 - ID: {}, 内容: {}", messageId, content);

        // 这里可以实现死信消息的特殊处理逻辑
        // 比如：记录到数据库、发送通知、人工干预等
    }

    private boolean executeBusinessLogic(String content) {
        // 模拟实际的业务处理逻辑
        // 这里可以根据消息内容执行不同的业务逻辑

        // 检查消息格式
        if (content == null || content.trim().isEmpty()) {
            return false;
        }

        // 模拟处理时间
        try {
            Thread.sleep(50); // 50ms 处理时间
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }

        // 模拟处理结果（80% 成功率）
        return Math.random() > 0.2;
    }

    // 统计信息获取方法
    public long getProcessedCount() {
        return processedCount.get();
    }

    public long getFailedCount() {
        return failedCount.get();
    }

    public long getDeadLetterCount() {
        return deadLetterCount.get();
    }

    public void resetCounters() {
        processedCount.set(0);
        failedCount.set(0);
        deadLetterCount.set(0);
    }
}